package com.whosly.fast.web.quickly.filter;

import com.whosly.fast.web.quickly.handler.LocalCachehandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.concurrent.atomic.AtomicLong;

public class ReactiveRateLimiter {
    private static final Logger logger = LoggerFactory.getLogger(ReactiveRateLimiter.class);

    private final LocalCachehandler cachehandler;

    private final int limitPerPeriod;
    private final Duration period;

    public ReactiveRateLimiter(LocalCachehandler cachehandler, int limitPerPeriod, Duration period) {
        this.cachehandler = cachehandler;
        this.limitPerPeriod = limitPerPeriod;
        this.period = period;
    }

    public Mono<Boolean> tryAcquire(String key) {
        return Mono.defer(() -> {
            // 尝试从缓存中获取计数器，如果不存在则创建一个新的
            AtomicLong counter = cachehandler.get(key);

            // 简单的限流逻辑：如果计数器小于限制，则增加并返回true；否则返回false
            if (counter.get() < limitPerPeriod) {
                boolean acquired = counter.compareAndSet(counter.get(), counter.get() + 1);
                if (acquired) {
                    // 可以选择在这里添加一个定时任务来重置计数器
                    return Mono.just(true);
                }
            }
            return Mono.just(false);
        });
    }
}
